package com.janlei.tdd.practise;

import com.google.common.collect.Maps;
import lombok.*;

import java.util.Map;
import java.util.Objects;

/**
 * 储物柜
 */
@Getter
public class StoreContentArk {

    private final Map<QRCode, Bag> context = Maps.newHashMap();

    /**
     * 存放包，得到二维码
     */
    public QRCode put(Bag bag) throws IllegalArgumentException {
        String owner = bag.getOwner();
        QRCode key = QRCode.getCode(owner);
        Bag used = context.get(key);
        if (used != null) {
            throw new IllegalArgumentException("当前获取柜已被使用！！！");
        }
        context.putIfAbsent(key, bag);
        return key;
    }

    /**
     * 扫描二维码，获取包
     */

    public Bag getBagBy(QRCode code) throws IllegalArgumentException {
        if (context.containsKey(code)) {
            Bag bag = context.get(code);
            context.remove(code);
            return bag;
        }
        throw new IllegalArgumentException("当前货柜中的物品已被取走，请关闭货柜！！！");
    }
}

@Getter
@Setter
@AllArgsConstructor
@ToString
@EqualsAndHashCode
class Bag {
    private String owner;
    private String message;
}

@Getter
@EqualsAndHashCode
class QRCode {
    private int id;
    private String owner;

    private QRCode(int id, String owner) {
        this.id = id;
        this.owner = owner;
    }

    public static QRCode getCode(String owner) {
        int hash = Objects.hash(owner);
        return new QRCode(hash, owner);
    }
}